package network.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;



public class EchoServer {
    // 创建socket对象
    private DatagramSocket socket;

    // 构造方法
    public EchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    // 启动服务器，完成主要的业务逻辑
    public void start() throws IOException {
        System.out.println();
        System.out.println("服务器启动!");
        while (true) {
            // 1.读取请求并解析
            // 1)创建一个空白的DatagramPacket对象
            DatagramPacket reqPacket = new DatagramPacket(new byte[4096], 4096);
            // 2)通过receive读取网卡的数据，如果网卡没有收到数据，就会阻塞等待
            socket.receive(reqPacket);
            // 3)把DatagramPacket中的数据解析成字符串
            String request = new String(reqPacket.getData(),0,reqPacket.getLength());
            // 2.根据请求计算响应
            String response = process(request);
            // 3.把响应写回到客户端
            // 1) 把响应数据构造成DatagramPacket对象 
            DatagramPacket respPacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                reqPacket.getSocketAddress());
            // 2) 把DatagramPacket发送回客户端
            socket.send(respPacket);
            //4.打印日志
            System.out.printf("[%s:%d] req: %s, resp: %s\n",
                reqPacket.getAddress(),reqPacket.getPort(),request,response);
        }
    }

    //由于我们是回显服务器，所以响应和请求是一样的，这里直接返回请求即可
    public String process(String request) {
        return request;
    }
    public static void main(String[] args) throws IOException {
        EchoServer server = new EchoServer(9090);
        server.start();
    }
}
